package com.ehotting.edsta.circuitDesign.service.impl;

import com.ehotting.eaf.core.domain.R;
import com.ehotting.eaf.core.utils.StringUtils;
import com.ehotting.edsta.system.api.RemoteFileService;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public abstract class InputStreamWorkbookHelper <T> {

    private RemoteFileService remoteFileService;

    public InputStreamWorkbookHelper() {}

    public InputStreamWorkbookHelper(RemoteFileService remoteFileService) {
        this.remoteFileService = remoteFileService;
    }

    // 下载excel表格
    public T invoke(String url) {
        InputStream inputStream = null;
        Workbook workbook = null;
        try {
            int index = StringUtils.ordinalIndexOf(url, "/", 1);
            String bucketName = url.substring(0,index);
            String filePath = url.substring(index + 1);
            if(StringUtils.isEmpty(filePath)){
                return null;
            }
            R<byte[]> bytesFromMinio = remoteFileService.getBytesFromMinio(filePath,bucketName);
            if(bytesFromMinio.getData() == null){
                return null;
            }
            inputStream = new ByteArrayInputStream(bytesFromMinio.getData());
            workbook = WorkbookFactory.create(inputStream);
            return run(workbook);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(workbook != null) {
                    workbook.close();
                }
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    public abstract T run(Workbook workbook);

}
